Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [9]:
# Load pickled data
import pickle

training_file = "train.p"
testing_file = "test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
x_train, y_train = train['features'], train['labels']
x_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below.

In [10]:
### Replace each question mark with the appropriate value.

# TODO: Number of training examples
n_train = len(x_train)

# TODO: Number of testing examples.
n_test = len(x_test)

# TODO: What's the shape of an traffic sign image?
image_shape = x_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = 43

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 39209
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [79]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

plt.axis('off')


import csv

sign_label_mapping = {}
with open("signnames.csv") as fh:
    reader = list(csv.reader(fh))
    sign_label_mapping = {int(k): v for k, v in reader[1:]}

label = y_train[0]

# figure out where in the x_train list certain images are located. They are unordered
# so go through everything and find examples of where each type of image is located
# in the list
image_type_indices = []

image_types = set()
for i, label_num in enumerate(y_train):
    if label_num not in image_types:
        image_type_indices.append((i, label_num))
        image_types.add(label_num)

# sort by the image type
image_type_indices.sort(key=lambda t: t[1])

fig, axes = plt.subplots(9, 5, figsize = (32, 32))

for index, image_num in image_type_indices:
    #print(i, y_train[i])
    axes.flat[image_num].imshow(x_train[index])
    axes.flat[image_num].axis('off')
    axes.flat[image_num].set_title(
        str(image_num) + " - " + sign_label_mapping[image_num], 
        fontsize=20)

    

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [12]:
### Preprocess the data here.
### Feel free to use as many code cells as needed.

from sklearn.utils import shuffle

x_train, y_train = shuffle(x_train, y_train)

from pprint import pprint as pp

print(len(x_train[1]))
#pp(x_train[0][0])
32

Question 1

Describe how you preprocessed the data. Why did you choose that technique?

Answer:

I used the shuffle method from sklearn which was lifted from the example solution. Shuffling randomly is usually pretty good in most situations where you need to mix up the data ordering.

In [13]:
### Generate additional data (OPTIONAL!)
### and split the data into training/validation/testing sets here.
### Feel free to use as many code cells as needed.

# take 20% of the images for validation
num_validation_images = int(n_test * 0.2)

print(len(x_test))
x_validation, y_validation = x_test[:num_validation_images], y_test[:num_validation_images]

x_test = x_test[num_validation_images:]
y_test = y_test[num_validation_images:]

print("Number of validation images:", num_validation_images)
print("New number of testing images:", len(x_test), len(y_test))
12630
Number of validation images: 2526
New number of testing images: 10104 10104

Question 2

Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?

Answer:

Pretty simple...just too 20% of the testing images and reserved them for validation.

In [14]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
import tensorflow as tf


from tensorflow.contrib.layers import flatten

def GermanSigns(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
    # changed input size from 32x32x1 to 32x32x3
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean=mu, stddev=sigma))
    conv1_b = tf.Variable(tf.zeros(6))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
    
    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # print(conv1)
    
    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(16))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    
    #print(conv2)
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # print(conv2)

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)
    
    #print("fc0", fc0)
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)
    
    #print("fc1", fc1)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(84))
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    #print("fc2", fc2)
    
    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = n_classes.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(n_classes))
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    #print("logits", logits)
    
    return logits
    

print("Num training images:", n_train)
print("Num validation images:", len(x_validation))
print("Num test images:", n_test)
Num training images: 39209
Num validation images: 2526
Num test images: 12630

Question 3

What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.

Answer:

This is fully lifted from the LeNet architecture. All I did were update the parameters accordingly to take into account 3 layers in the input for the RGB channels.

In [16]:
### Train your model here.
### Feel free to use as many code cells as needed.

x = tf.placeholder(tf.float32, (None, ) + image_shape)
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)

rate = 0.001

import time
name = str(int(time.time()))


logits = GermanSigns(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)


correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

EPOCHS = 30
BATCH_SIZE = 64


saver = tf.train.Saver()

def evaluate(x_data, y_data):
    num_examples = len(x_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = x_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        #print(batch_x, batch_y)
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
In [17]:
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(x_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        x_train, y_train = shuffle(x_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = x_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        validation_accuracy = evaluate(x_validation, y_validation)
        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './trafficsigns')
    print("Model saved")
Training...

EPOCH 1 ...
Validation Accuracy = 0.695

EPOCH 2 ...
Validation Accuracy = 0.813

EPOCH 3 ...
Validation Accuracy = 0.865

EPOCH 4 ...
Validation Accuracy = 0.835

EPOCH 5 ...
Validation Accuracy = 0.885

EPOCH 6 ...
Validation Accuracy = 0.881

EPOCH 7 ...
Validation Accuracy = 0.875

EPOCH 8 ...
Validation Accuracy = 0.887

EPOCH 9 ...
Validation Accuracy = 0.897

EPOCH 10 ...
Validation Accuracy = 0.894

EPOCH 11 ...
Validation Accuracy = 0.888

EPOCH 12 ...
Validation Accuracy = 0.909

EPOCH 13 ...
Validation Accuracy = 0.906

EPOCH 14 ...
Validation Accuracy = 0.901

EPOCH 15 ...
Validation Accuracy = 0.912

EPOCH 16 ...
Validation Accuracy = 0.901

EPOCH 17 ...
Validation Accuracy = 0.878

EPOCH 18 ...
Validation Accuracy = 0.916

EPOCH 19 ...
Validation Accuracy = 0.908

EPOCH 20 ...
Validation Accuracy = 0.916

EPOCH 21 ...
Validation Accuracy = 0.913

EPOCH 22 ...
Validation Accuracy = 0.911

EPOCH 23 ...
Validation Accuracy = 0.921

EPOCH 24 ...
Validation Accuracy = 0.924

EPOCH 25 ...
Validation Accuracy = 0.925

EPOCH 26 ...
Validation Accuracy = 0.918

EPOCH 27 ...
Validation Accuracy = 0.920

EPOCH 28 ...
Validation Accuracy = 0.920

EPOCH 29 ...
Validation Accuracy = 0.920

EPOCH 30 ...
Validation Accuracy = 0.932

Model saved

Question 4

How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)

Answer:

I used the same training as in the LeNet architecture. I did play with the training rate, epoch and batch size a bit. I found that increasing the epochs and lowering the batch size by 1/2 produced better accuracy than the original values. I also found that increasing the larning rate led to worse accuracy.

Question 5

What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.

Answer:

Mainly this was trial and error. I would have loved to have experimented with different CNN designs but just didn't have the time to go through that process.


Step 3: Test a Model on New Images

Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

Question 6

Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.

Answer:

In [18]:
### Run the predictions here.
### Feel free to use as many code cells as needed.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import tensorflow as tf


def test_on_test_data():
    with tf.Session() as sess:
        new_saver = tf.train.import_meta_graph('trafficsigns.meta')
        new_saver.restore(sess, tf.train.latest_checkpoint('./'))
        test_accuracy = evaluate(x_test, y_test)
        print("Test Accuracy = {:.3f}".format(test_accuracy))

test_on_test_data()
Test Accuracy = 0.922
In [105]:
import glob
import numpy as np
from scipy.misc import imresize


import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

files = sorted(glob.glob("street-signs/*"))
print(files)

include_training_image = False

expected_indices = [int(fn.split('-')[-1].strip('.jpg').lstrip('indx')) for fn in files]

images = [plt.imread(fn) for fn in files]
images = [imresize(img, [32, 32, 3]) for img in images]

# optionally included one of the trained images to ensure it results in a hit, making
# the accuracy go up...just a sanity check for the testing code below.
if include_training_image:
    expected_indices.append(y_train[0])
    images.append(x_train[0])

expected = np.array(expected_indices)

for img in images:
    assert img.shape == (32, 32, 3)
['street-signs/50-speed-limit-indx2.jpg', 'street-signs/50-speed-limit_2-indx2.jpg', 'street-signs/double-curve-indx21.jpg', 'street-signs/end-of-no-passwing-indx41.jpg', 'street-signs/keep-left-indx39.jpg', 'street-signs/no-entry-indx17.jpg', 'street-signs/road-work-indx25.jpg', 'street-signs/roundabout-indx40.jpg', 'street-signs/stop-indx14.jpg', 'street-signs/straight-or-right-indx36.jpg', 'street-signs/wild-animals-2-indx31.jpg', 'street-signs/wild-animals-indx31.jpg']
In [106]:
fig, axes = plt.subplots(3, 4, figsize =(32,32))

for i, img in enumerate(images):
    axes.flat[i].imshow(img)
    axes.flat[i].axis('off')
    axes.flat[i].set_title(
        str(expected[i]) + " - " + sign_label_mapping[expected[i]], 
        fontsize=30)
In [107]:
import glob
import numpy as np


with tf.Session() as sess:
    test_saver = tf.train.import_meta_graph('trafficsigns.meta')
    test_saver.restore(sess, tf.train.latest_checkpoint('./'))
    real_test_accuracy = evaluate(images, expected)
    print("Test Accuracy = {:.3f}".format(real_test_accuracy))
Test Accuracy = 0.333

Question 7

Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.

NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.

Answer:

It looks like the testing on different images didn't do so well with an accuraccy of only 25-30% (depending on which images I use). I think some of this could be due to the relatively poor image quality from the training set. I noticed the training set images looks a lot more blurry and washed out compared to the images i found on the web. Also, some of my images were at different angles which could have thrown the model for a loop.

In [100]:
thirty_one = np.array([31], dtype=np.uint8)
In [108]:
# see which images are predicted correctly
with tf.Session() as sess:
    s = tf.train.import_meta_graph('trafficsigns.meta')
    s.restore(sess, tf.train.latest_checkpoint('./'))
    for i in range(len(images)):
        result = sess.run(
            accuracy_operation,
            # feed_dict={x: images[i:i+1], y: thirty_one}
            feed_dict={x: images[i:i+1], y: expected[i:i+1]}
        )
        print(result, files[i])
1.0 street-signs/50-speed-limit-indx2.jpg
0.0 street-signs/50-speed-limit_2-indx2.jpg
0.0 street-signs/double-curve-indx21.jpg
0.0 street-signs/end-of-no-passwing-indx41.jpg
0.0 street-signs/keep-left-indx39.jpg
1.0 street-signs/no-entry-indx17.jpg
0.0 street-signs/road-work-indx25.jpg
1.0 street-signs/roundabout-indx40.jpg
0.0 street-signs/stop-indx14.jpg
0.0 street-signs/straight-or-right-indx36.jpg
0.0 street-signs/wild-animals-2-indx31.jpg
1.0 street-signs/wild-animals-indx31.jpg
In [ ]:
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.

Question 8

Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

Answer:

In [119]:
softmax_out = tf.nn.softmax(logits)

# see which images are predicted correctly
with tf.Session() as sess:
    s = tf.train.import_meta_graph('trafficsigns.meta')
    s.restore(sess, tf.train.latest_checkpoint('./'))
    
    softmax_prob = sess.run(softmax_out, feed_dict={x: images})
In [130]:
with tf.Session() as sess:
    result = sess.run(tf.nn.top_k(tf.constant(softmax_prob), k=5))
In [141]:
correct = 0
in_top = 0

for i, top_picks in enumerate(result.indices):
    e = expected[i]
    was_correct = e == top_picks[0]
    prediction_in_top = e in top_picks
    if was_correct:
        correct += 1
    if prediction_in_top:
        in_top += 1
        
print("Num correct: %s, accuracy: %0.3f" % (correct, correct / len(images)))
print("Number of images in top picks: %s, possible accuracy %0.3f" % (in_top, in_top / len(images)))
Num correct: 4, accuracy: 0.333
Number of images in top picks: 7, possible accuracy 0.583

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.